package com.aos.erp.message.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aos.dto.*;
import com.aos.erp.common.utils.StringUtils;
import com.aos.erp.message.dto.MessageRecordDTO;
import com.aos.erp.message.enums.PushStatus;
import com.aos.erp.message.enums.PushType;
import com.aos.erp.message.model.*;
import com.aos.erp.message.model.vo.MRConditionVo;
import com.aos.erp.message.remote.MQService;
import com.aos.erp.message.service.MessageRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@Async
public class MessageTaskTrigger {

    @Resource
    private MQService mqService;

    @Resource
    private MessageRecordService messageRecordService;

    @Value("${pushMessage.pushCount}")
    private int pushCount;

    // 推送消息（每两分钟发一次）
    @Scheduled(cron = "${pushMessage.pushScheduled}")
    public void pushMessage() {

        // 每次处理10条记录
        MRConditionVo conditionVo = new MRConditionVo();
        conditionVo.setPageSize(pushCount);
        List<MRWaitPushInfo> waitPushList = messageRecordService.findWaitSend(conditionVo);

        for (MRWaitPushInfo waitPushItem : waitPushList) {
            pushMessage(waitPushItem);
        }
    }

    // 处理推送结果（每分钟处理一次结果）
    @Scheduled(cron = "${pushMessage.pushResultScheduled}")
    public void pushMessageResult() {

        // 消费消息（每次处理1个？？）
        MessageConsumeDTO consumeDTO = new MessageConsumeDTO();
        consumeDTO.setQueueName("test_mq");
        consumeDTO.setTopic("test.MQ");
        consumeDTO.setExchange("school-web-service");
//        RespDTO<MessageDTO> result = mqService.consumeMessage(consumeDTO);
//        if(result.code == 0 && result.data != null){
//            MessageDTO messageDTO = result.data;
//            JSONObject jsonObject = messageDTO.getMessage();
//        }
    }

    private void pushMessage(MRWaitPushInfo waitPushItem) {
        log.info("推送" + waitPushItem.getPushTypeName() + "消息: " + waitPushItem.getMrRecipient());
        MessageRecordDTO messageRecordDTO = messageRecordService.getRecordDetail(waitPushItem.getId());
        PushType pushType = messageRecordDTO.getMessageRecord().getPushType();
//        if(pushType == PushType.app) {
//            pushAppMessage(messageRecordDTO);
//        } else if(pushType == PushType.wx_public) {
//            pushPublicMessage(messageRecordDTO);
//        } else if(pushType == PushType.wx_applet) {
//            pushAppletMessage(messageRecordDTO);
//        } else if(pushType == PushType.sms) {
//            pushSmsMessage(messageRecordDTO);
//        }
    }

    private void pushAppMessage(MessageRecordDTO messageRecordDTO) {
        MessageRecordInfo messageRecord = messageRecordDTO.getMessageRecord();
        MRContentAppInfo appInfo = messageRecordDTO.getContentAppInfo();

        // 封装消息基本信息
        AppPushDTO appPushDTO = new AppPushDTO();
        appPushDTO.setPushType(0);  //
        appPushDTO.setRegistrationId("");   // 来自第三方
        appPushDTO.setNotificationTitle(messageRecord.getMrTitle());
        appPushDTO.setMsgTitle(messageRecord.getMrTitle());
        appPushDTO.setMsgContent(messageRecord.getMrContent());
        appPushDTO.setExtParam(appInfo.getMrBizData()); // 扩展属性

        // 发送
        RespDTO<List<TMQResultDTO>> respDTO = mqService.sendAppTMQ(appPushDTO);

        // 响应结果
        log.info(JSON.toJSONString(respDTO));
        if(respDTO.code == 0) {
            messageRecordService.updatePushStatus(messageRecord.getId(), PushStatus.push_yes, JSON.toJSONString(respDTO));
        } else {
            messageRecordService.updatePushStatus(messageRecord.getId(), PushStatus.push_no, JSON.toJSONString(respDTO));
        }
    }

    /**
     * 公众号模板消息推送
     * @param messageRecordDTO
     */
    private void pushPublicMessage(MessageRecordDTO messageRecordDTO) {

//        RespDTO<List<TMQResultDTO>> sendTMQ( TMQSendDTO tmqSendDTO) 公众号模板消息推送

        MessageRecordInfo messageRecord = messageRecordDTO.getMessageRecord();
        MRContentWxPublicInfo wxPublicInfo = messageRecordDTO.getContentForPublic();

        // 封装消息基本信息
        WxMiniTemplateDTO wxMiniTemplateDTO = new WxMiniTemplateDTO();
        wxMiniTemplateDTO.setTemplateId(wxPublicInfo.getMrWxTemplateId());
        wxMiniTemplateDTO.setUrl(wxPublicInfo.getMrUrl());

        // 设置参数
        if(StringUtils.isNotEmpty(messageRecord.getMrMsgParams())) {
            JSONArray paramArray = JSONArray.parseArray(messageRecord.getMrMsgParams());
            if(paramArray.size() > 0) {
                Map<String, TemplateParam> dataParam = new HashMap<>();
                for (int i = 0; i < paramArray.size(); i++) {
                    JSONObject paramItem = paramArray.getJSONObject(i);
                    TemplateParam templateParam = new TemplateParam();
                    templateParam.setName(paramItem.getString("paramKey"));
                    templateParam.setValue(paramItem.getString("paramValue"));
                    dataParam.put(paramItem.getString("paramKey"), templateParam);
                }
                wxMiniTemplateDTO.setData(dataParam);
            }
        }

        // 设置接收用户
        List<String> toUserList = new ArrayList<>();
        toUserList.add(messageRecordDTO.getMessageRecord().getMrRecipientIdNo());
        wxMiniTemplateDTO.setToUserList(toUserList);

        // 发送
        RespDTO<List<TMQResultDTO>> respDTO = mqService.sendAppTMQ(wxMiniTemplateDTO);

        // 响应结果
        log.info(JSON.toJSONString(respDTO));
        if(respDTO.code == 0) {
            messageRecordService.updatePushStatus(messageRecord.getId(), PushStatus.push_yes, JSON.toJSONString(respDTO));
        } else {
            messageRecordService.updatePushStatus(messageRecord.getId(), PushStatus.push_no, JSON.toJSONString(respDTO));
        }
    }

    /**
     * 推送小程序消息
     * @param messageRecordDTO
     */
    private void pushAppletMessage(MessageRecordDTO messageRecordDTO) {
        MessageRecordInfo messageRecord = messageRecordDTO.getMessageRecord();
        MRContentWxAppletInfo wxAppletInfo = messageRecordDTO.getContentForApplet();

        // 封装消息基本信息
        WxMiniTemplateDTO wxMiniTemplateDTO = new WxMiniTemplateDTO();
        wxMiniTemplateDTO.setForm_id(wxAppletInfo.getMrFormId());
        wxMiniTemplateDTO.setTemplateId(wxAppletInfo.getMrWxTemplateId());
        wxMiniTemplateDTO.setUrl(wxAppletInfo.getMrUrl());

        // 设置参数
        if(StringUtils.isNotEmpty(messageRecord.getMrMsgParams())) {
            JSONArray paramArray = JSONArray.parseArray(messageRecord.getMrMsgParams());
            if(paramArray.size() > 0) {
                Map<String, TemplateParam> dataParam = new HashMap<>();
                for (int i = 0; i < paramArray.size(); i++) {
                    JSONObject paramItem = paramArray.getJSONObject(i);
                    TemplateParam templateParam = new TemplateParam();
                    templateParam.setName(paramItem.getString("paramKey"));
                    templateParam.setValue(paramItem.getString("paramValue"));
                    dataParam.put(paramItem.getString("paramKey"), templateParam);
                }
                wxMiniTemplateDTO.setData(dataParam);
            }
        }

        // 设置接收用户
        List<String> toUserList = new ArrayList<>();
        toUserList.add(messageRecordDTO.getMessageRecord().getMrRecipientIdNo());
        wxMiniTemplateDTO.setToUserList(toUserList);

        // 发送
        RespDTO<List<TMQResultDTO>> respDTO = mqService.sendAppTMQ(wxMiniTemplateDTO);

        // 响应结果
        log.info(JSON.toJSONString(respDTO));
        if(respDTO.code == 0) {
            messageRecordService.updatePushStatus(messageRecord.getId(), PushStatus.push_yes, JSON.toJSONString(respDTO));
        } else {
            messageRecordService.updatePushStatus(messageRecord.getId(), PushStatus.push_no, JSON.toJSONString(respDTO));
        }
    }

    private void pushSmsMessage(MessageRecordDTO messageRecordDTO) {
        MessageRecordInfo messageRecord = messageRecordDTO.getMessageRecord();
        MRContentSmsInfo smsInfo = messageRecordDTO.getContentForSms();

        // 封装消息基本信息
        SmsDTO smsDTO = new SmsDTO();
        smsDTO.setMobile(messageRecord.getMrRecipientPhone());
        smsDTO.setTempId(smsInfo.getMrSmsTemplateId());

        // 设置参数
        Map<String, Object> linkedMap = new HashMap<String, Object>();
        linkedMap.put("product","无纸化");
        if(StringUtils.isNotEmpty(messageRecord.getMrMsgParams())) {
            JSONArray paramArray = JSONArray.parseArray(messageRecord.getMrMsgParams());
            if(paramArray.size() > 0) {
                for (int i = 0; i < paramArray.size(); i++) {
                    JSONObject paramItem = paramArray.getJSONObject(i);
                    linkedMap.put(paramItem.getString("paramKey"), paramItem.getString("paramValue"));
                }
            }
        }
        smsDTO.setLinkedMap(linkedMap);

        // 发送
        RespDTO respDTO = mqService.sendSMS(smsDTO);

        // 响应结果
        log.info(JSON.toJSONString(respDTO));
        if(respDTO.code == 0) {
            messageRecordService.updatePushStatus(messageRecord.getId(), PushStatus.push_yes, JSON.toJSONString(respDTO));
        } else {
            messageRecordService.updatePushStatus(messageRecord.getId(), PushStatus.push_no, JSON.toJSONString(respDTO));
        }
    }

    public String sendSmsMsg(String recipientPhone, String smsTemplateId, String msgParams) {
        SmsDTO smsDTO = new SmsDTO();
        smsDTO.setMobile(recipientPhone);
        smsDTO.setTempId(smsTemplateId);

        Map<String, Object> linkedMap = new HashMap<String, Object>();
        JSONArray paramArray = JSONArray.parseArray(msgParams);
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject paramJSON = paramArray.getJSONObject(i);
            linkedMap.put(paramJSON.getString("paramKey"), paramJSON.getString("paramValue"));
        }
//        Map<String, Object> linkedMap = new HashMap<String, Object>();
//        linkedMap.put("code","asdhaisdh");
        linkedMap.put("product","无纸化");
        smsDTO.setLinkedMap(linkedMap);
        RespDTO respDTO = mqService.sendSMS(smsDTO);
        log.info(JSONObject.toJSONString(respDTO));
        return respDTO.toString();
    }
}
